package com.example.homework

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.example.homework.db.UserDBHelper
import com.example.homework.utils.Prefs

class ProfileFragment : Fragment(R.layout.fragment_profile) {

    private lateinit var tvHighScore: TextView
    private lateinit var tvUsername: TextView
    private lateinit var tvAccount: TextView
    private lateinit var ivAvatar: ImageView
    private lateinit var btnEdit: View

    /* 供外部刷新最高分 */
    fun refreshHighScore(newHigh: Int) {
        tvHighScore.text = "最高分：$newHigh"
        val account = Prefs.lastAccount(requireContext()) ?: return
        UserDBHelper(requireContext()).use { it.updateHighScore(account, newHigh) }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        tvUsername = view.findViewById(R.id.tv_username)
        tvAccount  = view.findViewById(R.id.tv_account)
        tvHighScore = view.findViewById(R.id.tv_high_score)
        ivAvatar    = view.findViewById(R.id.iv_avatar)
        btnEdit     = view.findViewById(R.id.btn_edit)

        loadUser()

        /* 跳转编辑页（forResult） */
        btnEdit.setOnClickListener {
            startForEdit.launch(Intent(requireContext(), ProfileEditActivity::class.java))
        }
    }

    /* 接收编辑页回传的新头像 URI 与昵称 */
    private val startForEdit =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                loadUser()          // 重新加载即可
            }
        }

    private fun loadUser() {
        val account = Prefs.lastAccount(requireContext())
        if (account.isNullOrEmpty()) {
            gotoLogin()
            return
        }

        UserDBHelper(requireContext()).use { db ->
            val user = db.getUserByAccount(account) ?: return@use
            tvUsername.text  = "用户名：${user.username}"
            tvAccount.text   = "账号：${user.account}"
            tvHighScore.text = "最高分：${user.highScore}"

            if (user.avatar.isNotEmpty()) {

                Glide.with(this)
                    .load(user.avatar)
                    .placeholder(R.drawable.ic_avatar_placeholder)
                    .error(R.drawable.ic_avatar_placeholder)
                    .into(ivAvatar)
                Log.d("ProfileFragment", "Avatar URL: ${user.avatar}")
            } else {
                ivAvatar.setImageResource(R.drawable.ic_avatar_placeholder)
            }
        }
    }

    private fun gotoLogin() {
        startActivity(Intent(requireContext(), LoginActivity::class.java))
        requireActivity().finish()
    }
}